package org.gruposp2p.proyectokarma.gwt.client.ui.vote;

import java.util.Set;
import org.gruposp2p.proyectokarma.gwt.client.domain.Tag;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.JsArray;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.Response;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import org.gruposp2p.proyectokarma.gwt.client.json.JSONToDomain;
import org.gruposp2p.proyectokarma.gwt.client.ui.ErrorDialog;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.json.client.JSONValue;
import com.allen_sauer.gwt.log.client.Log;
import com.google.gwt.visualization.client.AbstractDataTable;
import com.google.gwt.visualization.client.AbstractDataTable.ColumnType;
import com.google.gwt.visualization.client.DataTable;
import com.google.gwt.visualization.client.Selection;
import com.google.gwt.visualization.client.VisualizationUtils;
import com.google.gwt.visualization.client.events.SelectHandler;
import com.google.gwt.visualization.client.visualizations.PieChart;
import com.google.gwt.visualization.client.visualizations.PieChart.Options;

public class ResultsDialog {
    
    @UiField DialogBox dialogBox;
    @UiField VerticalPanel mainPanel;
    @UiField VerticalPanel chartContainer;
    @UiField Button acceptButton;
    @UiField VerticalPanel loadingPanel;
    
    private static ResultsDialogUiBinder uiBinder = GWT
                    .create(ResultsDialogUiBinder.class);

    interface ResultsDialogUiBinder extends
            UiBinder<Widget, ResultsDialog> {
    }

    public ResultsDialog() {
        uiBinder.createAndBindUi(this);
        setLoadingPanel(true);
        acceptButton.setStylePrimaryName("acceptButton");
        // Create a callback to be called when the visualization API
        // has been loaded.
        Runnable onLoadCallback = new Runnable() {
          public void run() {
            PieChart pie = new PieChart(createTable(), createOptions());
            pie.addSelectHandler(createSelectHandler(pie));
            chartContainer.add(pie);
            setLoadingPanel(false);
          }
        };

        // Load the visualization api, passing the onLoadCallback to be called
        // when loading is done.
        VisualizationUtils.loadVisualizationApi(onLoadCallback, PieChart.PACKAGE);
    }

    private SelectHandler createSelectHandler(final PieChart chart) {
        return new SelectHandler() {
          @Override
          public void onSelect(SelectEvent event) {
            String message = "";
            // May be multiple selections.
            JsArray<Selection> selections = chart.getSelections();
            for (int i = 0; i < selections.length(); i++) {
              // add a new line for each selection
              message += i == 0 ? "" : "\n";
              
              Selection selection = selections.get(i);

              if (selection.isCell()) {
                // isCell() returns true if a cell has been selected.
                
                // getRow() returns the row number of the selected cell.
                int row = selection.getRow();
                // getColumn() returns the column number of the selected cell.
                int column = selection.getColumn();
                message += "cell " + row + ":" + column + " selected";
              } else if (selection.isRow()) {
                // isRow() returns true if an entire row has been selected.
                
                // getRow() returns the row number of the selected row.
                int row = selection.getRow();
                message += "row " + row + " selected";
              } else {
                // unreachable
                message += "Pie chart selections should be either row selections or cell selections.";
                message += "  Other visualizations support column selections as well.";
              }
            }
            
            //Window.alert(message);
          }
        };
      }
    
    private Options createOptions() {
        Options options = Options.create();
        options.setWidth(400);
        options.setHeight(240);
        options.set3D(true);
        options.setTitle("My Daily Activities");
        return options;
      }
    
    public void show(int xPopupPos, int yPopupPos) {
        dialogBox.setPopupPosition(xPopupPos, yPopupPos);
        dialogBox.show();
    }
   
    @UiHandler("acceptButton")
    void handleAcceptButton(ClickEvent e) {
		dialogBox.hide();
    }
    
    private AbstractDataTable createTable() {
        DataTable data = DataTable.create();
        data.addColumn(ColumnType.STRING, "Task");
        data.addColumn(ColumnType.NUMBER, "Hours per Day");
        data.addRows(2);
        data.setValue(0, 0, "Work");
        data.setValue(0, 1, 14);
        data.setValue(1, 0, "Sleep");
        data.setValue(1, 1, 10);
        return data;
      }
    
    private class ServerRequestCallback implements RequestCallback {

        @Override
    	public void onError(Request request, Throwable exception) {
    		acceptButton.setEnabled(true);
        	new ErrorDialog().show("Exception", exception.getMessage());
        	Log.error(exception.getMessage());
    	}

        @Override
    	public void onResponseReceived(Request request, Response response) {
			Log.debug("StatusCode: " + response.getStatusCode() + 
					", Response Text: " + response.getText()); 
    		if (response.getStatusCode() == Response.SC_OK) {
                JSONValue jsonValue = JSONParser.parseLenient(response.getText());
    			Set<Tag> tagSet = JSONToDomain.getTags(jsonValue);
                //dialogBox.hide();
    		} else if (response.getStatusCode() == Response.SC_UNAUTHORIZED) {}
    		else {
            	loadingPanel.setVisible(false);
            	new ErrorDialog().show("Error", "Response status: " 
            			+ response.getStatusCode());
            	dialogBox.hide();
    		}
    	}

    }

    private void setLoadingPanel (boolean loading) {
        loadingPanel.setVisible(loading);
        chartContainer.setVisible(!loading);
    }
    
}